<template>
  <div>
    <!--添加用户弹框-->
    <el-dialog
      :title="isEdit ? '编辑用户' : '添加用户'"
      :visible.sync="dialogVisible"
      @close="handleDialogCancle('adminForm')"
      center
      width="800px"
    >
      <el-form
        :model="admin"
        ref="adminForm"
        :rules="adminRule"
        label-width="auto"
        size="small"
      >
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="姓名：" prop="nickName">
              <el-input
                v-model="admin.nickName"
                placeholder="请输入真实姓名"
                style="width: 250px"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属分公司" prop="deptId">
              <treeselect
                style="width: 250px"
                v-model="admin.deptId"
                :options="deptOptions"
                :normalizer="normalizer"
                placeholder="选择部门"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="帐号：" prop="username">
              <el-input
                v-model="admin.username"
                :disabled="isEdit"
                placeholder="请输入账号"
                style="width: 250px"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码：" prop="password">
              <el-input
                v-model="admin.password"
                type="password"
                placeholder="请输入密码"
                style="width: 250px"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="手机号：" prop="phoneNumber">
              <el-input
                v-model="admin.phoneNumber"
                placeholder="请输入手机号"
                style="width: 250px"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱：" prop="email">
              <el-input
                v-model="admin.email"
                placeholder="请输入邮箱"
                style="width: 250px"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="性别：" prop="gender">
              <el-select
                v-model="admin.gender"
                style="width: 250px"
                placeholder="请选择性别"
              >
                <el-option
                  v-for="item in sexOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态：">
              <el-radio-group v-model="admin.status">
                <el-radio :label="1">正常</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="角色：" prop="roleIds">
              <el-select
                v-model="admin.roleIds"
                multiple
                style="width: 250px"
                placeholder="请选择角色"
                size="small"
              >
                <el-option
                  v-for="item in allRoleList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12"> </el-col>
        </el-row>
        <el-form-item label="备注：" style="width: 100%">
          <el-input
            v-model="admin.note"
            placeholder="请输入备注"
            type="textarea"
            @input="textareaInputFun"
            :rows="5"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="handleDialogConfirm('adminForm')"
          size="small"
          >确 定</el-button
        >
        <el-button @click="handleDialogCancle('adminForm')" size="small"
          >取 消</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listDept } from "@/api/dept";
import { fetchAllRoleList } from "@/api/role";
import { handleTree } from "@/utils/auth";
import { createAdmin, updateAdmin } from "@/api/login";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
// 默认表单数据初始值
const defaultAdmin = {
  adminId: null,
  username: null,
  password: null,
  nickName: null,
  email: null,
  note: null,
  status: 1,
  gender: null,
  phoneNumber: null,
  roleIds: null
};
export default {
  components: { Treeselect },
  props: {
    // 弹框是否打开
    dialogVisible: {
      type: Boolean,
      default: () => false
    },
    // 是否为编辑状态
    isEdit: {
      type: Boolean,
      default: () => false
    }
  },
  data() {
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号不能为空"));
      } else {
        const reg = /^1[3-9][0-9]\d{8}$/;
        // 这里定义的reg变量没有加引号，所以是一种特殊的数据类型，即正则，可以直接用test()方法
        if (reg.test(value)) {
          callback();
        } else {
          // 具体错误信息没有提示
          return callback(new Error("请输入正确的手机号"));
        }
      }
    };
    var checkUserName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("用户名不能为空"));
      } else {
        const reg = /^[A-Za-z]+$|^\d+$|^[A-Za-z\d]+$/;
        if (reg.test(value)) {
          callback();
        } else {
          return callback(
            new Error("请检查格式，例如 字母 / 数字 / 字母+数字")
          );
        }
      }
    };
    return {
      admin: Object.assign({}, defaultAdmin),
      adminRule: {
        nickName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        deptId: [
          { required: true, message: "请选择所属分公司", trigger: "blur" }
        ],
        phoneNumber: [
          {
            required: true,
            min: 11,
            message: "手机号不足11位",
            trigger: "blur"
          },
          { validator: checkPhone, trigger: "blur" }
        ],
        username: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { validator: checkUserName, trigger: "blur" }
        ],
        // email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }]
      },
      // 部门树选项
      deptOptions: [],
      sexOptions: [
        { value: "1", label: "男" },
        { value: "2", label: "女" }
      ],
      allRoleList: []
    };
  },
  created() {
    // this.getAllRoleList();
  },
  methods: {
    openlogin(val) {
      this.getAffilcation();
      this.admin = val;
      // this.admin.deptName = this.admin.deptId
      this.admin.gender = this.admin.gender === 1 ? "男" : "女";
    },
    // 添加用户弹框确认按钮
    handleDialogConfirm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let msg = this.isEdit ? "是确认修改?" : "是确认添加?";
          this.$confirm(msg, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            if (this.isEdit) {
              // 编辑更新
              if (this.admin.gender === "男") {
                this.admin.gender = 1;
              }
              if (this.admin.gender === "女") {
                this.admin.gender = 2;
              }
              updateAdmin(this.admin.adminId, this.admin).then(response => {
                this.$message({
                  message: "修改成功！",
                  type: "success"
                });
                this.$emit("cancleDialog", false);
                this.$parent.getList();
              });
            } else {
              // 用户新增
              if (this.admin.gender == null) {
                this.admin.gender = 0;
              }
              createAdmin(this.admin).then(response => {
                this.$message({
                  message: "添加成功！",
                  type: "success"
                });
                this.$emit("cancleDialog", false);
                this.$parent.getList();
              });
            }
          });
        } else {
          // console.log("error submit!!");
          return false;
        }
      });
    },
    // 添加用户弹框取消按钮
    handleDialogCancle(formName) {
      this.$refs[formName].resetFields();
      this.cleanForm();
      this.$emit("cancleDialog", false);
    },
    // 将表单数据初始化
    cleanForm() {
      this.admin = Object.assign({}, defaultAdmin);
    },
    getAffilcation() {
      listDept().then(response => {
        this.deptOptions = handleTree(response.data.list, "deptId");
        this.getAllRoleList();
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    // 查询角色列表
    getAllRoleList() {
      console.log("kkkk");
      fetchAllRoleList().then(response => {
        this.allRoleList = response.data;
      });
    },
    // 备注输入框input输入事件
    textareaInputFun(val) {
      // 禁止文本框中输入尖括号之类的标签
      let replaceVal = val.replace(/<\/?[^>]+(>|$)/g, "");
      this.admin.note = replaceVal;
    }
  }
};
</script>

<style lang="scss" scoped></style>
